#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys
import os
import warnings
import time
import gc
import platform

def get_resource_path(relative_path):
    """获取资源文件的绝对路径，兼容开发环境和打包环境"""
    if hasattr(sys, '_MEIPASS'):
        # PyInstaller打包环境
        return os.path.join(sys._MEIPASS, relative_path)  # type: ignore
    elif getattr(sys, 'frozen', False) and hasattr(sys, 'executable'):
        # Nuitka打包环境 - 修正路径处理
        if os.path.basename(sys.executable).lower().endswith('.exe'):
            # 如果是exe文件，使用exe所在目录
            base_path = os.path.dirname(sys.executable)
        else:
            # 其他情况使用当前工作目录
            base_path = os.getcwd()
        return os.path.join(base_path, relative_path)
    else:
        # 开发环境
        return os.path.join(os.path.dirname(os.path.abspath(__file__)), relative_path)

# 检查Windows版本，避免使用Windows 7不支持的API
def check_windows_compatibility():
    if sys.platform == "win32":
        version = platform.version()
        major, minor, build = map(int, version.split('.'))
        # Windows 7是6.1版本
        if major < 6 or (major == 6 and minor < 2):
            # Windows 7或更早版本，禁用某些可能导致问题的功能
            os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = ''
            # 禁用可能引起问题的警告
            warnings.filterwarnings("ignore", category=DeprecationWarning)
            warnings.filterwarnings("ignore", module="cryptography")
            warnings.filterwarnings("ignore", module="paramiko")
            
            warnings.filterwarnings("ignore", message=".*deprecated.*")
            return False
    return True

# 在导入任何其他模块之前，先设置警告过滤
warnings.filterwarnings("ignore", category=UserWarning)
warnings.filterwarnings("ignore", category=DeprecationWarning)
warnings.filterwarnings("ignore", module="cryptography")
warnings.filterwarnings("ignore", module="paramiko")
warnings.filterwarnings("ignore", message=".*TripleDES.*")
warnings.filterwarnings("ignore", message=".*deprecated.*")

# Windows兼容性检查
is_win7_compatible = check_windows_compatibility()

# 添加错误处理
try:
    from PySide2.QtWidgets import QApplication
    from PySide2.QtCore import Qt, QThread, QObject, Signal, Slot, QTimer
    from ui.main_window import MainWindow
    
    # 全局线程跟踪器
    class ThreadTracker(QObject):
        threads = []
        
        @classmethod
        def add_thread(cls, thread, worker=None):
            """添加线程到跟踪列表"""
            if thread not in [t[0] for t in cls.threads]:
                cls.threads.append((thread, worker))
        
        @classmethod
        def remove_thread(cls, thread):
            """从跟踪列表中移除线程"""
            cls.threads = [(t, w) for t, w in cls.threads if t != thread]
        
        @classmethod
        def cleanup_all_threads(cls):
            """清理所有跟踪的线程"""
            remaining_threads = []
            
            for thread, worker in cls.threads:
                try:
                    if thread and thread.isRunning():
                        thread.quit()
                        if not thread.wait(1000):  # 增加等待时间
                            thread.terminate()
                            thread.wait(500)
                        remaining_threads.append((thread, worker))
                    
                    if worker:
                        worker.deleteLater()
                    
                    if thread:
                        thread.deleteLater()
                except (RuntimeError, AttributeError):
                    pass
            
            cls.threads = remaining_threads
            return len(remaining_threads) == 0
except ImportError as e:
    print(f"导入PySide2失败: {e}")
    print("请确保已正确安装PySide6: pip install PySide2")
    sys.exit(1)

def main():
    try:
        app = QApplication(sys.argv)
        window = MainWindow()
        window.show()
        
        # 确保应用程序退出时清理所有资源
        result = app.exec_()
        
        # 在应用程序退出前，强制关闭所有窗口
        app.closeAllWindows()
        
        # 1. 使用ThreadTracker进行主要清理
        print("开始使用ThreadTracker清理线程...")
        all_cleaned = False
        for attempt in range(5):  # 增加尝试次数
            all_cleaned = ThreadTracker.cleanup_all_threads()
            if all_cleaned:
                print(f"第{attempt+1}次尝试: 所有线程已清理完毕")
                break
            print(f"第{attempt+1}次尝试: 仍有线程需要清理，再次尝试...")
            time.sleep(0.2)  # 增加等待时间后再次尝试
        
        # 2. 如果ThreadTracker清理不彻底，使用全局垃圾回收和线程遍历作为后备
        if not all_cleaned:
            print("ThreadTracker清理不彻底，进行额外清理...")
            
            # 多次清理循环，确保所有线程都被正确终止
            for attempt in range(5):  # 增加尝试次数
                threads_found = False
                for obj in gc.get_objects():
                    try:
                        if isinstance(obj, QThread) and hasattr(obj, 'isRunning') and obj.isRunning():
                            threads_found = True
                            print(f"发现运行中的线程: {obj}")
                            try:
                                obj.quit()
                                if not obj.wait(1000):  # 增加等待时间
                                    obj.terminate()
                                    obj.wait(500)
                                obj.deleteLater()
                            except RuntimeError:
                                print(f"警告: 尝试终止线程{obj}时发生RuntimeError")
                            except Exception as e:
                                print(f"警告: 尝试终止线程{obj}时发生错误: {e}")
                    except (RuntimeError, AttributeError):
                        pass
                
                if not threads_found:
                    break
                
                # 强制垃圾回收
                gc.collect()
                time.sleep(0.2)  # 增加等待时间
        
        # 3. 最后进行彻底的垃圾回收和等待
        gc.collect()
        time.sleep(0.5)  # 增加等待时间给系统完成清理
        
        # 4. 最终检查是否仍有运行中的线程
        remaining_threads = 0
        for obj in gc.get_objects():
            try:
                if isinstance(obj, QThread) and hasattr(obj, 'isRunning') and obj.isRunning():
                    remaining_threads += 1
                    print(f"警告: 程序退出时仍有线程在运行: {obj}")
            except (RuntimeError, AttributeError):
                pass
        
        if remaining_threads > 0:
            print(f"警告: 共有{remaining_threads}个线程在程序退出时仍在运行")
            # 即使有残留线程，我们也继续退出程序，因为已经做了所有可能的清理尝试
        
        sys.exit(result)
    except Exception as e:
        print(f"程序运行出错: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)

if __name__ == '__main__':
    main()